package com.zbkj.front.controller;

import cn.hutool.core.util.ObjectUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.zbkj.common.exception.CrmebException;
import com.zbkj.common.model.Group;
import com.zbkj.common.model.GroupMember;
import com.zbkj.common.model.together.*;
import com.zbkj.common.model.user.User;
import com.zbkj.common.request.TogetherExamRequest;
import com.zbkj.common.result.CommonResult;
import com.zbkj.service.dao.GroupMessageDTO;
import com.zbkj.service.service.*;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.transaction.support.TransactionTemplate;
import org.springframework.web.bind.annotation.*;

import java.time.LocalDate;
import java.time.LocalDateTime;
import java.time.ZoneId;
import java.time.ZonedDateTime;
import java.util.Date;
import java.util.List;

@Slf4j
@RestController
@RequestMapping("api/front/together")
@Api(tags = "共创试稿控制器")
public class TogetherExamController {

    @Autowired
    private TogetherJobExamService togetherJobExamService;

    @Autowired
    private UserTogetherService userTogetherService;

    @Autowired
    private TogetherJobService togetherJobService;

    @Autowired
    private UserService userService;

    @Autowired
    private TransactionTemplate transactionTemplate;

    @Autowired
    private UserTagService userTagService;

    @Autowired
    private IGroupService groupService;

    @Autowired
    private IGroupMemberService groupMemberService;

    @Autowired
    private UserTogetherRecordService userTogetherRecordService;

    @Autowired
    private IGroupMessageService groupMessageService;


    @ApiOperation(value = "新增试稿")
    @RequestMapping(value = "/exam/add", method = RequestMethod.POST)
    public CommonResult<TogetherJobExam> add(@RequestBody TogetherExamRequest request){

        Integer userid = userService.getUserIdException();

        LambdaQueryWrapper<TogetherJob> lqw = new LambdaQueryWrapper<>();
        lqw.eq(TogetherJob::getTogetherId,request.getTogetherId());
        lqw.eq(TogetherJob::getJobId,request.getJobId());
        TogetherJob togetherJob = togetherJobService.getOne(lqw);
       //查找共创角色表
        if(ObjectUtil.isNull(togetherJob)){
            throw new CrmebException("查无此角色");
        }
        //查找当前试稿数量
        LambdaQueryWrapper<TogetherJobExam> lqw2 = new LambdaQueryWrapper<>();
        lqw2.eq(TogetherJobExam::getTogetherJobId,togetherJob.getId());
        lqw2.eq(TogetherJobExam::getIsDel,false);
        List<TogetherJobExam> list = togetherJobExamService.list(lqw2);
        if(list.size()>=3){
            throw new CrmebException("已达当前试稿人数上限");
        }

        //添加试稿请求的
        TogetherJobExam togetherJobExam = new TogetherJobExam();
        BeanUtils.copyProperties(request,togetherJobExam);
        // 获取当前日期和时间
        LocalDateTime currentDateTime = LocalDateTime.now();
        // 计算12小时后的日期和时间
        LocalDateTime dateTimeAfter12Hours = currentDateTime.plusHours(12);

        // 转换为 ZonedDateTime
        ZonedDateTime zonedDateTime = dateTimeAfter12Hours.atZone(ZoneId.systemDefault());
        // 转换为 Date
        Date dateAfter12Hours = Date.from(zonedDateTime.toInstant());

        togetherJobExam.setLimitNum(request.getLimitTime()==null? request.getLimitTime(): Integer.valueOf(3));
        togetherJobExam.setLimitTime(dateAfter12Hours);
        togetherJobExam.setStatus(0);
        togetherJobExam.setSuid(userid);
        togetherJobExam.setTogetherJobId(togetherJob.getId());
        togetherJobExamService.save(togetherJobExam);

        return CommonResult.success(togetherJobExam);
    }

    @ApiOperation(value = "上传试稿")
    @RequestMapping(value = "/exam/update/upload", method = RequestMethod.POST)
    public CommonResult<String> upload(@RequestBody TogetherExamRequest request){

        Integer userId = userService.getUserIdException();

        LambdaQueryWrapper<TogetherJobExam> lqw = new LambdaQueryWrapper<>();
        lqw.eq(TogetherJobExam::getUid,userId);
        lqw.eq(TogetherJobExam::getId,request.getId());
        TogetherJobExam togetherJobExam =togetherJobExamService.getOne(lqw);

        if(ObjectUtil.isNull(togetherJobExam))
            throw new CrmebException("查无此记录");

        togetherJobExam.setFurl(request.getFurl());
        togetherJobExam.setStatus(2);
        if(togetherJobExamService.updateById(togetherJobExam))
            return CommonResult.success("状态更新成功");
        else return CommonResult.failed("发送错误");
    }

    @ApiOperation(value = "判断是否试稿中")
    @RequestMapping(value = "/isExam", method = RequestMethod.GET)
    public CommonResult<TogetherJobExam> isExam(@RequestParam Integer uid){
        Integer userId = userService.getUserIdException();
        TogetherJobExam togetherJobExam = togetherJobExamService.getByDUid(uid,userId);

        //不是试稿
        if(ObjectUtil.isNull(togetherJobExam))
            return CommonResult.success(togetherJobExam);

        //查项目信息
        TogetherJob togetherJob = togetherJobService.getById(togetherJobExam.getTogetherJobId());
        togetherJobExam.setUserTag(userTagService.getById(togetherJob.getJobId()));
        togetherJobExam.setUserTogether(userTogetherService.getById(togetherJob.getTogetherId()));

        return CommonResult.success(togetherJobExam);
    }
    @ApiOperation(value = "试稿邀请处理")
    @RequestMapping(value = "/exam/handleInv", method = RequestMethod.POST)
    public CommonResult<String> handleInv(@RequestBody TogetherJobExam request ){
        return CommonResult.success(togetherJobExamService.handle(request));
    }


    @ApiOperation(value = "试稿确认")
    @RequestMapping(value = "/exam/update/confirm", method = RequestMethod.POST)
    public CommonResult<String> confirm(@RequestBody TogetherExamRequest request){

        Integer userId = userService.getUserIdException();

        LambdaQueryWrapper<TogetherJobExam> lqw = new LambdaQueryWrapper<>();
//        lqw.eq(TogetherJobExam::getSuid,userId);
        lqw.eq(TogetherJobExam::getId,request.getId());
//        lqw.eq(TogetherJobExam::getIsDel,0);
        TogetherJobExam togetherJobExam = togetherJobExamService.getOne(lqw);
        if(ObjectUtil.isNull(togetherJobExam))
            throw  new CrmebException("查无记录");

        if(request.getStatus() == 3){

            togetherJobExam.setStatus(3);
            TogetherJob togetherJob = togetherJobService.getById(togetherJobExam.getTogetherJobId());
            togetherJob.setUid(togetherJobExam.getUid());
            togetherJob.setStatus(3);

            UserTogether userTogether = userTogetherService.getById(togetherJob.getTogetherId());

            //查群
            LambdaQueryWrapper<Group> groupLambdaQueryWrapper = new LambdaQueryWrapper<>();
            groupLambdaQueryWrapper.eq(Group::getTogetherId,userTogether.getId());
            groupLambdaQueryWrapper.eq(Group::getDeleted,0);
            Group group = groupService.getOne(groupLambdaQueryWrapper);

            //查是否在群
            LambdaQueryWrapper<GroupMember> memberLambdaQueryWrapper = new LambdaQueryWrapper<>();
            memberLambdaQueryWrapper.eq(GroupMember::getGroupId,group.getId());
            memberLambdaQueryWrapper.eq(GroupMember::getUserId,togetherJobExam.getUid());
            GroupMember gm = groupMemberService.getOne(memberLambdaQueryWrapper);
            User user = userService.getById(togetherJobExam.getUid());
            //进群

            UserTogetherRecord userTogetherRecord = new UserTogetherRecord();
            userTogetherRecord.setContent(user.getNickname()+"加入了共创");
            userTogetherRecord.setImg(user.getAvatar());
            userTogetherRecord.setTogetherId(userTogether.getId());
            userTogetherRecord.setType(3);
            userTogetherRecord.setUid(togetherJobExam.getUid());

            GroupMessageDTO messageDTO=new GroupMessageDTO();
            messageDTO.setGroupId(group.getId().longValue());
            messageDTO.setType(0);
            messageDTO.setContent(user.getNickname());
            messageDTO.setUserId(togetherJobExam.getUid().longValue());
            messageDTO.setSendNickName(user.getNickname());


            Boolean flag = transactionTemplate.execute(e->{
                try {
                    if(gm==null){
                        GroupMember groupMember = new GroupMember();
                        groupMember.setGroupId(group.getId());
                        groupMember.setUserId(Long.valueOf(togetherJobExam.getUid()));
                        groupMember.setHeadImage(user.getAvatar());
                        groupMember.setAliasName(user.getNickname());
//            groupMember.setRemark(StringUtils.isEmpty(vo.getRemark()) ? group.getName() : vo.getRemark());
                        groupMemberService.save(groupMember);
                    }
                    groupMessageService.sendUserMessage(messageDTO);
                    userTogetherRecordService.save(userTogetherRecord);
                    togetherJobService.updateById(togetherJob);
                    togetherJobExamService.updateById(togetherJobExam);
                    return Boolean.TRUE;
                }catch (Exception exception){
                    return Boolean.FALSE;
                }
            });
            if(Boolean.TRUE.equals(flag))
                return CommonResult.success("状态更新成功");
            else return CommonResult.failed("发生错误");
        }else if(request.getStatus() == 4){
            togetherJobExam.setStatus(4);
            togetherJobExamService.updateById(togetherJobExam);
            return CommonResult.success("状态更新成功");
        }else {
            throw new CrmebException("参数错误");
        }
    }

}
